<div class="mt-9 max-w-md">
  <div class="grid grid-cols-1 gap-6">
    {#if isLogin && wallet!=""}
     <span>钱包地址： {wallet}</span>
     {:else}
     <MButton on:click={connect} title="连接钱包"/>
    {/if}

    <MTextInput  bind:value={receive}   placeholder="接收人地址"/>
    <MTextInput  bind:value={token}   placeholder="转移代币类型"/>
    <MTextInput  bind:value={amount}   placeholder="转移数量"/>
      <MButton on:click={withdraw} title="提币"/>
      <MTextInput  bind:value={uuid}   placeholder="提议ID"/>
      <select  bind:value={opinion} class="block w-full mt-1 rounded-md bg-gray-100 border-transparent focus:border-gray-500 focus:bg-white focus:ring-0">
        <option value={1}>赞同</option>
        <option value={2}>反对</option>
      </select>

    <MButton on:click={vote} title="投票"/>

    <hr/>
    <MTextInput  bind:value={voter_address}   placeholder="投票人地址"/>
    <MButton on:click={addVoter} title="添加投票人"/>
    <MButton on:click={removeVoter} title="移除投票人"/>

    <hr/>
    <MTextInput  bind:value={pTitle}   placeholder="提议标题"/>
    <MTextInput  bind:value={pContent}   placeholder="提议详情"/>
    <MTextInput  bind:value={pToken}   placeholder="代币合约地址"/>
    <MTextInput  bind:value={pAddress}   placeholder="接收代币的地址"/>
    <MTextInput  bind:value={pAmount}   placeholder="数量"/>
    <MButton on:click={createWithDrawProposal} title="创建提币提议"/>

    <hr/>
    <MButton on:click={addVoter} title="创建添加投票人提议"/>
    <MButton on:click={removeVoter} title="创建删除投票人提议"/>

    <MTextInput  bind:value={uuidOnChain}   placeholder="提议ID"/>
    <MButton on:click={readProposal} title="读取提议详情"/>
    <dd class="text-gray-600 text-sm" style="opacity: 1;">链上数据：{greetOnChain}</dd>
  </div>
</div>


<script lang="ts">
  import {abi} from '../../constants'
  import MButton from '../../components/MButton.svelte'
  import MTextInput from '../../components/MTextInput.svelte'
  let greet = '';
  let greetOnChain = ""

  let isLogin =false
  let wallet = ""

  let opinion=1
  let uuid = ""
  let uuidOnChain=""
  let contract = null

  let voter_address=""


  let receive=""
  let amount = ""
  let token = ""

  let pToken=""
  let pTitle=""
  let pContent=""
  let pAmount=""
  let pAddress=""


  const connect = ()=>{
    if (window.ethereum) {
      window.ethereum
        .request({ method: "eth_requestAccounts" })
        .then((accounts)=>{
          if (accounts.length === 0) {
      // MetaMask is locked or the user has not connected any accounts
      swal({
        title: "出现错误",
        text: "未检测到 Metamask 插件，如你已经安装请启用并刷新页面!",
        icon: "error",
        button: "确认",
      });
      } else {
        wallet=accounts[0] 
        isLogin=true
        if (window.ethereum) {
        let web3 = new Web3(window.ethereum);
        contract = new web3.eth.Contract(abi,"0x5FC8d32690cc91D4c39d9d3abcBD16989F875707",{
          from:wallet
         })
      }
      
      }
        })
        .catch((err) => {
          swal({
        title: "出现错误",
        text: "未检测到 Metamask 插件，如你已经安装请启用并刷新页面!",
        icon: "error",
        button: "确认",
      });

      console.error(err);
        });
    } else {
      swal({
        title: "出现错误",
        text: "未检测到 Metamask 插件，如你已经安装请启用并刷新页面!",
        icon: "error",
        button: "确认",
      });
    }
  
  }


  const readProposal = async ()=>{
    isContractExisted();
    if(uuidOnChain==""){
      swal({
        title: "出现错误",
        text: "提议ID不能为空",
        icon: "error",
        button: "确认",
      });
      return false;
    }
    const proposal_detail_basic  = await contract.methods.proposal_detail_basic(uuidOnChain).call()
    const approve_votes = await contract.methods.approve_votes().call()

    console.log({proposal_detail_basic})
  }

  const read = async () => {
    isContractExisted();
    console.log("读取链上数据")
    try {
    const getVoters = await contract.methods.getVoters().call();
    getVoters.forEach(async element => {
      const voter_right_map = await contract.methods.voter_right_map(element).call();
      console.log({element,voter_right_map})
    });
 

    const getProposalList  = await contract.methods.getProposalList().call()
    console.log({getProposalList})

    getProposalList.forEach(async element => {
      
      const proposal_detail  = await contract.methods.proposal_detail(element).call()

      const getApproveVotes = await contract.methods.getApproveVotes(element).call()
      const getRejectVotes = await contract.methods.getRejectVotes(element).call()
    console.log({proposal_detail,getApproveVotes,getRejectVotes})

    });

    console.log({ getVoters });
    console.log(getVoters.length)

      greetOnChain = getVoters
  } catch (e) {
    console.log(e);
  }
  }


  const addVoter =async  ()=>{
    isContractExisted();
    try{
      console.log("添加投票人", voter_address)
    const addVoter = await contract.methods.addVoter(voter_address).send({});
    console.log({ addVoter });
    }catch(e){
      console.error(e)
    }
  }


  const removeVoter =async  ()=>{
    isContractExisted();
    try{
      console.log("移除投票人", voter_address)
    const removeVoter = await contract.methods.removeVoter(voter_address).send({});
    console.log({ removeVoter });
    }catch(e){
      console.error(e)
    }
}

const withdraw = async ()=>{
  isContractExisted();
  try{
      console.log("提币", token,receive,amount)
    const withdraw = await contract.methods.withdraw( token,receive,amount).send({});
    console.log({ withdraw });
    }catch(e){
      console.error(e)
    }
}

const createWithDrawProposal = async ()=>{

}

const vote = async ()=>{
  isContractExisted();
  try{
    console.log("投票", uuid,opinion)
    if(uuid==""||opinion==""){
      swal({
        title: "出现错误",
        text: "提议ID 或观点不能未空",
        icon: "error",
        button: "确认",
      });
      return false;
    }
    const vote = await contract.methods.vote( uuid,opinion).send({});
    console.log({ vote });
    }catch(e){
      console.error(e)
    }
}


const isContractExisted = ()=>{
  if(!contract){
    swal({
        title: "出现错误",
        text: "未登录，请点击登录按钮",
        icon: "error",
        button: "确认",
      });
  }
}
 
</script>